#!/usr/bin/env python
# encoding: utf-8

from PyQt5.QtWidgets import QFileDialog, QWidget, QMessageBox
# from PyQt5.QtCore import *
import pysnooper

import os
import re
import time
import json
from common.libs.Log import logger
from common.libs.ymodem.YModem import YModem
# from common.libs.Helper import getCurrentTime
from ui.upgrade import Ui_Form
from ..mqtt_client.MqttThread import MqttThread
from ..mqtt_client.MqttSetDialog import MqttSetDialog
import qtawesome as qta

# from .ymodem import YModem
import threading

tx = 'smcrl/00000113/tx'
rx = 'smcrl/00000113/rx'


class UpgradeWidget(QWidget, Ui_Form):
    ymodem_recv_buf = ''
    openfile_name = ''

    def __init__(self, parent=None):
        super(QWidget, self).__init__(parent)
        self.setupUi(self)
        self.mqtt = MqttThread()
        self.ymodem_sender = YModem(self.sender_getc, self.sender_putc)
        self.uiInit()
        # self.layoutInit()
        self.signalInit()

        # self.ymodem_recv_buf = ''

    def layoutInit(self):
        self.setLayout(self.gridLayout)

    def uiInit(self):
        self.mqttSetDialog = MqttSetDialog()
        # 图片
        self.connect_icon = qta.icon('fa5s.circle', color='springgreen')
        self.disconnect_icon = qta.icon('fa5s.circle', color='red')
        self.pushButton_mqtt_connect.setIcon(self.disconnect_icon)

    def timerInit(self):
        pass

    def signalInit(self):
        self.mqtt.signal_on_message.connect(self.mqttOnMessage)
        self.mqtt.signal_on_connect.connect(self.mqttOnConnect)
        self.mqtt.signal_on_disconnect.connect(self.mqttOnDisconnect)
        self.pushButton_mqtt_set.clicked.connect(self.mqttSetDialog.show)
        self.pushButton_mqtt_connect.clicked.connect(self.mqttDoConnect)
        self.pushButton_openfile.clicked.connect(self.openFile)
        self.pushButton_upgrade.clicked.connect(self.doUpgrade)
        pass

    def openFile(self):
        openfile_name = QFileDialog.getOpenFileName(
            self, '选择文件', '', 'bin files(*.bin)', 'all(*.*)')
        self.openfile_name = openfile_name[0]
        self.label_file_path.setText(openfile_name[0])

    def doUpgrade(self):
        if self.openfile_name:
            self.upgrade_thread = threading.Thread(
                target=self.upgradeThread, args=(self.openfile_name,))
            self.upgrade_thread.setDaemon(True)
            self.upgrade_thread.start()
        else:
            logger.info('未选择文件')
            QMessageBox.information(self, "提示", "请选择文件！", QMessageBox.Yes)

    # @pysnooper.snoop()
    def upgradeThread(self, file):
        self.mqtt.do_publish(self.lineEdit_pub.text(),
                             json.dumps({"code": "400", "msg": "1"}), 0)
        time.sleep(1)
        while True:
            try:
                res = json.loads(self.ymodem_recv_buf)
                logger.info(res)
                if res['aswcode'] == '400':
                    self.ymodem_recv_buf = ''
                    break
                else:
                    logger.info("信息错误")
            except Exception as e:
                logger.info(e)
                return
        self.ymodem_sender.send_file(file, retry=3, callback=self.upgrade_callback)

    # @pysnooper.snoop()
    def sender_getc(self, size):
        if len(self.ymodem_recv_buf) > 0:
            buf = bytes(self.ymodem_recv_buf[:size], encoding='utf-8')
            self.ymodem_recv_buf = self.ymodem_recv_buf[size:]
            return buf or None
        # pass

    # @pysnooper.snoop()
    def sender_putc(self, data):
        # self.mqtt.do_publish('stmcrtl/00000001/tx', data, 0)
        logger.info("putc:")
        logger.info(data)
        self.mqtt.do_publish(self.lineEdit_pub.text(), data, 0)
        pass

    def upgrade_callback(self, total_packets, file_size, file_name):
        print("callback:")
        print(total_packets)
        print(file_size)
        print(file_name)
        pass
        # if len(progress_bar.gettags("text")) == 0:
        #     progress_bar.create_text(175, 15, text=file_name, tags="text")
        # progress = total_packets*350/(file_size/1024)
        # progress_bar.coords(fill_line, (0, 0, progress, 30))

    def mqttDoConnect(self):
        if not self.mqtt.is_connect:
            conf = self.mqttSetDialog.config
            self.mqtt.load_conf(conf)
            self.mqtt.start()
        else:
            QMessageBox.information(self, "提示", "已连接服务器！", QMessageBox.Yes)

    def mqttDoDisconnect(self):
        self.mqtt.stop()

    def mqttOnConnect(self):
        self.pushButton_mqtt_connect.setIcon(self.connect_icon)
        logger.info('连接服务器')
        self.mqtt.do_subscribe([(self.lineEdit_sub.text(), 0)])
        logger.info('订阅成功')

    def mqttOnDisconnect(self):
        # self.pushButton_mqtt_connect.setIcon(self.disconnect_icon)
        logger.info('连接断开')
        for i, device in enumerate(self.devices):
            self.devices_box_list[i].onlineStatusChange(0)

    def mqttOnSubscribe(self):
        logger.info('订阅成功')

    def mqttOnMessage(self, topic, message, qos):
        logger.info("[mqtt<-收到消息:]")
        logger.info('topic:%s' % topic)
        logger.info('message:%s' % message)
        logger.info('qos:%s' % qos)
        self.ymodem_recv_buf = message
        # res = re.match('fsc/(.*?)/([a-zA-Z0-9]{8,16})/tx', topic, re.M | re.I)
        # if res is None:
        #     return
        # model = res.group(1)
        # sn = res.group(2)
